package com.ichoice.rabbitmq.rpc.helper.service;

import com.ichoice.rabbitmq.rpc.helper.consts.CommonContant;
import com.ichoice.rabbitmq.rpc.helper.util.MqMetadataUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.Connection;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xianrensawang
 */
@Slf4j
public class ServerBlinding {

    private final CachingConnectionFactory cachingConnectionFactory;

    public ServerBlinding(CachingConnectionFactory cachingConnectionFactory) {
        this.cachingConnectionFactory = cachingConnectionFactory;
    }


    public void init(String appName) {
        String exchange = CommonContant.EXCHANGE;
        blind(exchange, appName);
    }

    /**
     * 绑定当前服务的消费队列
     *
     * @param exchange 统一的交换机
     * @param appName      当前服务名
     */
    public void blind(String exchange, String appName) {
        Connection connection = cachingConnectionFactory.createConnection();
        final Channel channel = connection.createChannel(false);
        try {
            channel.exchangeDeclare(exchange, "topic", true);
            channel.queueDeclare(MqMetadataUtils.selfQueue(appName), true, false, false, null);
            channel.queueBind(MqMetadataUtils.selfQueue(appName), exchange, MqMetadataUtils.selfKey(appName));
            // 只绑定关系,不绑定消费者,消费者绑定在ExecuteBlinding里实现
        } catch (IOException e) {
            log.error("channel添加队列失败" + MqMetadataUtils.selfQueue(appName));
        }
        // 配置延迟消息队列
        Map<String, Object> exchangeConfig = new HashMap<>();
        exchangeConfig.put("x-delayed-type", "direct");
        // 配置延迟队列跟key
        try {
            channel.exchangeDeclare(CommonContant.EXCHANGE_DELAY, "x-delayed-message", true, false, exchangeConfig);
            channel.queueDeclare(MqMetadataUtils.selfDelayQueue(appName), true, false, false, null);
            channel.queueBind(MqMetadataUtils.selfDelayQueue(appName), CommonContant.EXCHANGE_DELAY, MqMetadataUtils.selfDelayKey(appName));
            // 只绑定关系,不绑定消费者,消费者绑定在ExecuteBlinding里实现
        } catch (IOException e) {
            log.error("channel添加队列失败,请安装并启用延迟队列插件:{}", e.getMessage());
        }
    }

}